<template>
  <div
    :style="{
      width: obj.width + 'px',
      height: obj.height + 'px',
      backgroundColor: obj.color
    }"
  >
    <formComponent
      :element="activeData"
      :active-id="choose"
      :copy="copy"
      :delete="del"
      :form="form"
      :choose="chooseComponent"
      @click.stop="chooseComponent(activeData)"
    ></formComponent>
  </div>
</template>

<script lang="ts">
export default {
  name: 'divComponent'
}
</script>

<script lang="ts" setup>
import formComponent from '../../components/formComponent.vue'
import { ref, toRefs } from 'vue'
import { type Basis } from '@/types/element'

const props = defineProps<{
  obj: Basis
}>()

const { obj } = toRefs(props)
const form = ref([])
const activeData = ref({} as Basis)
const choose = ref('0')
// 选中组件
const chooseComponent = (element: Basis) => {
  console.log(element)
  activeData.value = element
  choose.value = element.field
}

// 获取随机ticks作为id
const getId = () => {
  return (
    (Math.floor(Math.random() * (99999 - 10000)) + 10000).toString() +
    new Date().getTime().toString().substring(5)
  )
}

// 删除组件
const del = (list: Array<Basis>, id: string) => {
  let delIdx = list.findIndex((i) => i.field === id) as number
  if (delIdx >= 0) list.splice(delIdx, 1)
  if (choose.value === id) {
    activeData.value = {} as Basis
    choose.value = '0'
  }
  if (!form.value.length) {
    activeData.value = {} as Basis
    choose.value = '0'
  }
}

// 复制组件
const copy = (list: Array<[Basis]>, node: any) => {
  let copIndex = list.findIndex((i: any) => i.field === node.field)
  list.splice(copIndex + 1, 0, clone(node))
}

// 克隆组件
const clone = (obj: Object) => {
  let cloneCp = reactive(JSON.parse(JSON.stringify(obj)))
  cloneCp.field = getId()
  return cloneCp
}
</script>
<style scoped></style>
